package com.xintoucloud.gsv.controller;

import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.xintoucloud.gsv.entity.User;
import com.xintoucloud.gsv.model.Node;
import com.xintoucloud.gsv.service.MenuService;
import com.xintoucloud.gsv.service.UserService;

@Controller
public class LoginController {
	@Autowired
	private UserService userService;
	
	@Autowired
	private MenuService menuService;
	
	@RequestMapping("/toLogin")
	public String toLoginPage(HttpSession session,Model m) {
		String Message=(String) session.getAttribute("LoginFail");
		m.addAttribute("msg", Message);
		session.invalidate();
		return "login";
	}
	@RequestMapping("/list")
	public String toHome(HttpSession session,Model m) {
		User user=(User) session.getAttribute("User");
		List <Node> nodes=menuService.listNodeByParentId(0,user.getRole().getRid());
		m.addAttribute("nodes", nodes);
		return "index";
	}
	@PostMapping("/login")
	public String Login(String uname,String upass,HttpSession session,Model m,HttpServletRequest request,HttpServletResponse response) {
		//System.out.println("uname:"+uname+",upass"+upass);
		if(!uname.trim().equals("")&&!upass.trim().equals("")&&uname!=null&&upass!=null) {
			User user = userService.login(uname, upass);
			if(user!=null) {
				session.setAttribute("User", user);
				//System.out.println("xxxxxxxxxxxxxxxxxxx:="+user.getRole().getRid());
				List <Node> nodes=menuService.listNodeByParentId(0,user.getRole().getRid());
				//System.out.println("nodes:=="+nodes);
				m.addAttribute("nodes", nodes);
				return "redirect:/list";
			}else {
				session.setAttribute("LoginFail", "登录失败!请检查账号密码是否输入正确");
				return "redirect:/toLogin";
			}
		}
		session.setAttribute("LoginFail","账号密码不能为空，请重新输入");
		return "redirect:/toLogin";	
	}
	@RequestMapping("/loginOut")
	public String loginOut(HttpSession session,HttpServletRequest request,HttpServletResponse response) {
		//删除自动登录的Cookie
		/*Cookie[] cookies = request.getCookies();
		if(cookies != null){
			for(Cookie c : cookies){
				String name = c.getName();
				if(name.equals("logindPid")||name.equals("JSESSIONID")){
					c.setMaxAge(0);
					//重写发送
					response.addCookie(c);
					break;
				}
			}
		}*/
		
		session.invalidate();
		return "redirect:toLogin";
	}
}
